//
//  MYGTopicViewController.swift
//  MYDoctor
//
//  Created by Denny on 2024/3/19.
//

import UIKit
import MJRefresh

class MYGTopicViewController: MYGBaseController {
    var sortKey = -1
    var serachBView: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F5F5F5")
        control.addCorner(radius: 17.5)
        return control
    }()
    var page = 1
    var dataSource = [MYGTopicModel]()
    var total = ""
    lazy var addBtn: UIButton = {
        let control = UIButton()
        control.setImage(UIImage.init(named: "MYG_addTopic"), for: .normal)
        control.addTarget(self, action: #selector(tapAddAction), for: .touchUpInside)
        return control
    }()
    lazy var searchTextField: UITextField = {
        let control = UITextField()
        control.textAlignment = .center
        control.placeholder = "搜索"
        control.delegate = self
        control.clearButtonMode = .whileEditing
        control.returnKeyType = .search
        return control
    }()
    
    lazy var sortBtn: UIButton = {
        let control = UIButton()
        control.setImage(UIImage.init(named: "MYG_topic_sort"), for: .normal)
        control.addTarget(self, action: #selector(tapSort), for: .touchUpInside)
        return control
    }()
    
    lazy var tableView: UITableView = {
        let control = UITableView()
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.estimatedRowHeight = 170
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(UINib.init(nibName: "MYGTopicTableViewCell", bundle: nil), forCellReuseIdentifier: "MYGTopicTableViewCell")
        control.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getList()
        })
        
        control.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getList()
        })
        return control
    }()
    
   @objc func getList() {
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGTopicModel>>.request(target: .articleTopicList(param: [
           "page":"\(self.page)",
           "pageSize":"20",
           "key":self.searchTextField.text ?? "",
           "sort":"\(self.sortKey + 1)"])) { item in
               self.tableView.mj_header?.endRefreshing()
               if item.page.page == 1 {
                   self.dataSource = item.list
               } else {
                   self.dataSource.append(contentsOf: item.list)
               }
               
               self.total = "\(item.page.total)"
               
               if item.page.total <= self.dataSource.count {
                   self.tableView.mj_footer?.endRefreshingWithNoMoreData()
               } else {
                   self.tableView.mj_footer?.endRefreshing()
               }
               
           self.tableView.reloadData()
       } failed: { _, error in
           MYGLoading.hide()
           MMYGHUD.showToast(text: error)
       }
   }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "话题圈子"
        view.backgroundColor = .white
        view.addSubview(sortBtn)
        sortBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: 47, height: 35))
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(23)
        }
        view.addSubview(serachBView)
        serachBView.snp.makeConstraints { make in
            make.right.equalTo(sortBtn.snp.left)
            make.top.equalToSuperview().offset(23)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(35)
        }
        
        serachBView.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(11)
            make.right.equalToSuperview().offset(-11)
            make.top.bottom.equalToSuperview()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(serachBView.snp.bottom).offset(15)
            make.left.right.bottom.equalToSuperview()
        }
        self.tableView.mj_header?.beginRefreshing()
        
        view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: 76, height: 76))
            make.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-bottomSafeheight - 61)
        }
        NotificationCenter.default.addObserver(self, selector: #selector(getList), name: Notification.Name("MYGTopicViewController_refresh"), object: nil)
    }
    
    @objc func tapAddAction() {
        if ((MYGUserManager.getUser()?.doctor.name.isEmpty) == true) || MYGUserManager.getUser()?.doctor.gender == 0 || ((MYGUserManager.getUser()?.doctor.identity.isEmpty) == true) {
            let vc = MYGBaseInfoController()
//            vc.model = model
            self.navigationController?.pushViewController(vc)
            return
        }
        
        let phone = MYGUserManager.getUser()?.doctor.phone ?? 0
        MMYGNetwork<MYGMicrosrationApi,MYGUserDoctor>.request(target: .get_doctor_phone_info(phone: "\(phone)")) { model  in
            MYGLoading.hide()
            guard let item = model else {return}
            
            let user = MYGUserManager.getUser()
            user?.doctor = item
            MYGUserManager.saveUser(user!)
//
//            let vc = MYGUpdateInfoViewController()
//            vc.model = user
//            self.navigationController?.pushViewController(vc)
            
            if MYGUserManager.isDoctorInfComplete  {
                if MYGUserManager.getUser()?.doctor.status == 20 {
                    let vc = MYGAddTopicViewController()
                    self.navigationController?.pushViewController(vc)
                }else {
                    MMYGHUD.showToast(text: "正在审核中，暂时无法使用该功能")
                }
        
            }else {
                let vc = MYGUpdateInfoViewController()
                vc.model = MYGUserManager.getUser()!
                vc.isEdit = true
                self.navigationController?.pushViewController(vc)
            }
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
        
      
        
       
    }
    @objc func tapSort() {
        YBPopupMenu.show(at: CGPoint(x: screenWidth - 25, y: navHeight + statusBarHeight + 58), titles: ["时间","热度"], icons: [], menuWidth: 61) { menu in
            menu?.delegate = self
            menu?.dismissOnSelected = true
            menu?.font = UIFont.regular(12)
            menu?.itemHeight = 30
            menu?.selectecIndex = self.sortKey
            menu?.selectedTextColor = UIColor.init(hexString: "#6389F1")
            menu?.separatorColor = .clear
            menu?.textColor = UIColor.init(hexString: "#C0BEBE")
        }
    }
}

extension MYGTopicViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        self.tableView.mj_header?.beginRefreshing()
        return true
    }
}

extension MYGTopicViewController:YBPopupMenuDelegate {
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        if index == self.sortKey {
            self.sortKey = -1//再次选中就清空
        }else {
            self.sortKey = index
        }
     
        self.tableView.mj_header?.beginRefreshing()
    }
}

extension MYGTopicViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGTopicTableViewCell", for: indexPath) as! MYGTopicTableViewCell
        let model = self.dataSource[indexPath.row]
        cell.bindData(model)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.row]
        let vc = MYGTopicDetailViewController()
        vc.id = model.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
